<template>
  <div class="upms-head">
    <a-row>
      <a-col :xs="{span:24}" :sm="{span:24}" :md="{span:6}" :lg="{span:5}" :xxl="{span:4}" class="header-left">
        <div class="upms-head-txt">
          {{userInfo.tenantName ? userInfo.tenantName : '通用权限管理系统 '}}
        </div>
      </a-col>
      <a-col :xs="{span:0}" :sm="{span:0}" :md="{span:18}" :lg="{span:19}" :xxl="{span:20}">
        <a-menu v-model="current" mode="horizontal">
          <a-menu-item v-for="menu in menuList" :key="menu.menuCode" style="float: left;"
                       @click="handleClick(menu.menuCode)" v-if="menu.menuId">
            <a-icon type="appstore"/>
            {{menu.menuName}}
          </a-menu-item>
          <a-sub-menu style="float: right">
            <span slot="title" class="submenu-title-wrapper">
              <a-avatar :src="avatar"/>
              {{userInfo.memberName ? userInfo.memberName : userInfo.account}}
              <a-icon type="down"/></span>
            <a-menu-item key="setting:1" @click="updateModal.visible = true">修改密码</a-menu-item>
            <a-menu-item key="setting:2" @click="showDefault">设置默认配置</a-menu-item>
            <a-menu-item key="setting:3" @click="handleClick('userCenter')">个人中心</a-menu-item>
            <a-menu-item key="setting:4">
              <div @click="Logout">退出登陆</div>
            </a-menu-item>
          </a-sub-menu>
          <a-sub-menu style="float: right">
            <span slot="title" class="submenu-title-wrapper"><a-icon type="bars"/>{{userInfo.orgName}}<a-icon
                type="down"/></span>
            <a-menu-item v-for="orgItem in userInfo.orgList" :key="orgItem.id"
                         @click="changeDefaultOrgTab(orgItem.id)">
              {{orgItem.name}}
            </a-menu-item>
          </a-sub-menu>
          <a-sub-menu style="float: right" v-if="!updateMemberDefaultInfo.showAllRole">
            <span slot="title" class="submenu-title-wrapper"><a-icon type="coffee"/>{{userInfo.roleName}}<a-icon
                type="down"/></span>
            <a-menu-item v-for="roleItem in userInfo.roleList" :key="roleItem.id"
                         @click="changeDefaultRoleTab(roleItem.id)">
              {{roleItem.name}}
            </a-menu-item>
          </a-sub-menu>
        </a-menu>
      </a-col>
    </a-row>
    <a-modal v-model="modal.visible" title="修改默认值" @cancel="cancel" :afterClose="afterClose">
      <a-form>
        <a-form-item label="是否显示全角色菜单" :label-col="modal.labelCol" :wrapper-col="modal.wrapperCol">
          <a-switch checkedChildren="是" unCheckedChildren="否" v-model="updateMemberDefaultInfo.showAllRole"
                    @change="changeShowAllRole"/>
        </a-form-item>
        <a-form-item label="默认角色" :label-col="modal.labelCol" :wrapper-col="modal.wrapperCol"
                     v-if="!updateMemberDefaultInfo.showAllRole">
          <a-select placeholder="请选择默认角色" v-model="updateMemberDefaultInfo.defaultRoleId" @change="changeDefaultRole">
            <a-select-option v-for="roleItem in userInfo.roleList" :key="roleItem.id" :value="roleItem.id">
              {{roleItem.name}}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="是否显示全组织机构菜单" :label-col="modal.labelCol" :wrapper-col="modal.wrapperCol"
                     v-if="updateMemberDefaultInfo.showAllRole">
          <a-switch checkedChildren="是" unCheckedChildren="否" v-model="updateMemberDefaultInfo.showAllOrg"
                    @change="changeShowAllOrg"/>
        </a-form-item>
        <a-form-item label="默认组织机构" :label-col="modal.labelCol" :wrapper-col="modal.wrapperCol">
          <a-select placeholder="请选择默认组织机构" @change="changeDefaultOrg" :style="modal.style"
                    v-model="updateMemberDefaultInfo.defaultOrgId">
            <a-select-option v-for="orgItem in orgList" :key="orgItem.id" :value="orgItem.id">
              {{orgItem.name}}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
      <template slot="footer">
        <a-button key="submit" type="primary" :loading="modal.loading" @click="updateMemberDefaultInfoOk">
          确定
        </a-button>
        <a-button key="back" @click="cancel">关闭</a-button>
      </template>
    </a-modal>
    <a-modal v-model="updateModal.visible" title="修改密码">
      <a-form :form="updateModal.form">
        <a-form-item label="成员账号" :label-col="modal.labelCol" :wrapper-col="modal.wrapperCol">
          <a-input placeholder="请输入成员账号！"
                   v-decorator="['username', {rules: [{ required: true, message: '请输入成员账号！'}]}]"/>
        </a-form-item>
        <a-form-item label="旧密码" :label-col="modal.labelCol" :wrapper-col="modal.wrapperCol">
          <a-input placeholder="请输入旧密码！" type="password"
                   v-decorator="['password', {rules: [{ required: true, message: '请输入旧密码！'}]}]"/>
        </a-form-item>
        <a-form-item label="新密码" :label-col="modal.labelCol" :wrapper-col="modal.wrapperCol">
          <a-input placeholder="请输入新密码！" type="password"
                   v-decorator="['newPassword', {rules: [{ required: true, message: '请输入新密码！'}]}]"/>
        </a-form-item>
        <a-form-item label="确认密码" :label-col="modal.labelCol" :wrapper-col="modal.wrapperCol">
          <a-input placeholder="请输入确认密码！" type="password"
                   v-decorator="['confirmPassword', {rules: [{ required: true, message: '请输入确认密码！'}, {
              validator: compareToFirstPassword,
            }]}]"/>
        </a-form-item>
      </a-form>
      <template slot="footer">
        <a-button key="submit" type="primary" :loading="modal.loading" @click="updatePwdOk">
          确定
        </a-button>
        <a-button key="back" @click="modal.visible = false">取消</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script>
  import Vue from 'vue'
  import {ACCESS_TOKEN, SELECT_HEAD, SELECT_LEFT, USER_INFO} from '../store/mutation-types'

  export default {
    name: 'UpmsHeader',
    components: {
      Vue
    },
    data () {
      return {
        current: ['userCenter'],
        width: this.$store.state.screenWidth - 200,
        userInfo: {},
        avatar: '',
        menuList: [],
        orgList: [],
        updateMemberDefaultInfo: {
          memberId: null,
          showAllRole: null,
          showAllOrg: null,
          defaultRoleId: null,
          defaultOrgId: null
        },
        modal: {
          visible: false,
          style: 'border: 0px solid red',
          labelCol: {span: 10},
          wrapperCol: {span: 14},
          loading: false
        },
        updateModal: {
          form: this.$form.createForm(this),
          visible: false,
          loading: false
        }
      }
    },
    mounted () {
      console.log('mounted Vue.ls.get(USER_INFO)', Vue.ls.get(USER_INFO))
      console.log('mounted user-info', this.$store.state.userInfo)
      this.$store.state.userInfo = Vue.ls.get(USER_INFO)
      this.userInfo = Vue.ls.get(USER_INFO)
      this.$store.state.operator = {
        tenantId: this.userInfo.tenantId,
        orgId: this.userInfo.orgId,
        memberId: this.userInfo.memberId,
        userId: this.userInfo.userId
      }
      this.menuList = this.userInfo.menuTree
      if (!Vue.ls.get(SELECT_HEAD)) {
        this.$store.state.selectHead = this.userInfo.menuTree[0].menuCode
      } else {
        this.$store.state.selectHead = Vue.ls.get(SELECT_HEAD)
      }
      this.current[0] = this.$store.state.selectHead
      this.init()
    },
    watch: {
      '$store.state.userInfo' () {
        console.log('upmsHeader $store.state.userInfo', this.$store.state.userInfo)
        this.userInfo = this.$store.state.userInfo
        this.menuList = this.userInfo.menuTree
        if (!Vue.ls.get(SELECT_HEAD)) {
          this.$store.state.selectHead = this.userInfo.menuTree[0].menuCode
        } else {
          this.$store.state.selectHead = Vue.ls.get(SELECT_HEAD)
        }
        this.current[0] = this.$store.state.selectHead
        this.init()
      },
      '$store.state.userInfo.avatar' () {
        this.userInfo.avatar = this.$store.state.userInfo.avatar
        this.userInfo.avatarThumb = this.$store.state.userInfo.avatarThumb
      },
      '$store.state.screenWidth' () {
        this.width = this.$store.state.screenWidth - 200
      }
    },
    methods: {
      // 退出登陆
      Logout () {
        this.$store.dispatch('Logout')
        Vue.ls.set(SELECT_HEAD, null)
        Vue.ls.set(SELECT_LEFT, null)
        Vue.ls.set(USER_INFO, null)
        Vue.ls.set(ACCESS_TOKEN, null)
        this.$store.state.selectHead = null
      },
      handleClick (menuCode) {
        this.current[0] = menuCode
        this.$store.state.selectHead = menuCode
        Vue.ls.set(SELECT_LEFT, null)
        Vue.ls.set(SELECT_HEAD, menuCode)
      },
      showDefault () {
        this.modal.visible = true
      },
      init () {
        if (this.userInfo.avatar) {
          this.avatar = this.userInfo.avatarThumb
        }
        this.updateMemberDefaultInfo.memberId = this.userInfo.memberId
        this.updateMemberDefaultInfo.showAllRole = this.userInfo.showAllRole === 1
        this.updateMemberDefaultInfo.showAllOrg = this.userInfo.showAllOrg === 1
        this.updateMemberDefaultInfo.defaultRoleId = this.userInfo.roleId
        this.updateMemberDefaultInfo.defaultOrgId = this.userInfo.orgId
        this.initUpdateMemberDefaultInfo()
      },
      // 初始化更新成员默认信息
      initUpdateMemberDefaultInfo () {
        console.log('initUpdateMemberDefaultInfo')
        this.userInfo.roleList.forEach(item => {
          if (item.id === this.userInfo.roleId) {
            this.userInfo.roleName = item.name
          }
        })
        this.orgList = []
        if (this.updateMemberDefaultInfo.showAllRole) {
          for (let key in this.userInfo.roleOrgMap) {
            for (let idName of this.userInfo.roleOrgMap[key]) {
              let tempList = []
              tempList.push(...this.orgList)
              let has = false
              for (let org of tempList) {
                if (idName.id === org.id) {
                  has = true
                  break
                }
              }
              if (!has) {
                this.orgList.push(idName)
              }
            }
          }
        } else {
          this.orgList.push(...this.userInfo.roleOrgMap[this.userInfo.roleId])
        }
        this.orgList.forEach(item => {
          if (item.id === this.updateMemberDefaultInfo.defaultOrgId) {
            this.userInfo.orgName = item.name
          }
        })
        this.modal.style = 'border: 0px solid red'
        if (this.updateMemberDefaultInfo.defaultOrgId == null) {
          this.modal.style = 'border: 1px solid red'
          this.modal.visible = true
        }
      },
      // 切换是否显示全角色权限
      changeShowAllRole (showAllRole) {
        console.log('changeShowAllRole', showAllRole)
        this.updateMemberDefaultInfo.showAllRole = showAllRole
        this.initUpdateMemberDefaultInfo()
      },
      // 切换是否显示全组织机构权限
      changeShowAllOrg (showAllOrg) {
        this.updateMemberDefaultInfo.showAllOrg = showAllOrg
        this.initUpdateMemberDefaultInfo()
      },
      // 切换默认角色
      changeDefaultRole (roleId) {
        console.log('changeDefaultRole roleId', roleId)
        this.orgList = []
        console.log('changeDefaultRole this.userInfo.roleOrgMap[roleId]', this.userInfo.roleOrgMap[roleId])
        this.orgList.push(...this.userInfo.roleOrgMap[roleId])
        this.modal.style = 'border: 1px solid red'
        let that = this
        let has = false
        this.orgList.forEach(org => {
          if (org.id === that.updateMemberDefaultInfo.defaultOrgId) {
            that.updateMemberDefaultInfo.defaultOrgId = org.id
            has = true
            that.modal.style = 'border: 0px solid red'
          }
        })
        if (!has) {
          this.updateMemberDefaultInfo.defaultOrgId = null
        }
      },
      // 切换默认角色
      changeDefaultRoleTab (roleId) {
        if (this.updateMemberDefaultInfo.defaultRoleId === roleId) {
          return
        }
        this.updateMemberDefaultInfo.defaultRoleId = roleId
        this.orgList = []
        this.orgList.push(...this.userInfo.roleOrgMap[roleId])
        this.modal.style = 'border: 1px solid red'
        let that = this
        let has = false
        this.orgList.forEach(org => {
          if (org.id === that.updateMemberDefaultInfo.defaultOrgId) {
            that.updateMemberDefaultInfo.defaultOrgId = org.id
            has = true
            that.modal.style = 'border: 0px solid red'
          }
        })
        if (!has) {
          this.updateMemberDefaultInfo.defaultOrgId = null
          this.modal.style = 'border: 1px solid red'
          this.modal.visible = true
        } else {
          this.updateMemberDefaultInfoOk()
        }
      },
      // 切换默认组织机构
      changeDefaultOrg (orgId) {
        this.updateMemberDefaultInfo.defaultOrgId = orgId
        this.modal.style = 'border: 0px solid red'
        let orgList = this.userInfo.roleOrgMap[this.updateMemberDefaultInfo.defaultRoleId]
        for (let i = 0; i < orgList.length; i++) {
          if (orgList[i].id === orgId) {
            this.userInfo.orgName = orgList[i].name
          }
        }
        if (this.updateMemberDefaultInfo.showAllRole) {
          for (let key in this.userInfo.roleOrgMap) {
            this.userInfo.roleOrgMap[key].forEach(org => {
              if (org.id === orgId) {
                this.updateMemberDefaultInfo.defaultRoleId = Number(key)
              }
            })
          }
        }
      },
      // 切换默认组织机构
      changeDefaultOrgTab (orgId) {
        this.updateMemberDefaultInfo.defaultOrgId = orgId
        this.modal.style = 'border: 0px solid red'
        let orgList = this.userInfo.roleOrgMap[this.updateMemberDefaultInfo.defaultRoleId]
        for (let i = 0; i < orgList.length; i++) {
          if (orgList[i].id === orgId) {
            this.userInfo.orgName = orgList[i].name
          }
        }
        if (this.updateMemberDefaultInfo.showAllRole) {
          for (let key in this.userInfo.roleOrgMap) {
            this.userInfo.roleOrgMap[key].forEach(org => {
              if (org.id === orgId) {
                this.updateMemberDefaultInfo.defaultRoleId = Number(key)
              }
            })
          }
        }
        this.updateMemberDefaultInfoOk()
      },
      // 更新成员默认信息
      updateMemberDefaultInfoOk () {
        if (this.updateMemberDefaultInfo.defaultOrgId == null) {
          this.$message.error('请设置默认组织机构')
          return
        }
        this.http.post('upmsApi', '/memberCenter/updateMemberDefaultInfo', {
          memberId: this.updateMemberDefaultInfo.memberId,
          showAllRole: this.updateMemberDefaultInfo.showAllRole ? 1 : 0,
          showAllOrg: this.updateMemberDefaultInfo.showAllOrg ? 1 : 0,
          defaultRoleId: this.updateMemberDefaultInfo.defaultRoleId,
          defaultOrgId: this.updateMemberDefaultInfo.defaultOrgId
        }).then((res) => {
          if (res.success) {
            this.$store.dispatch('getUserInfo')
            this.modal.visible = false
            Vue.ls.set(SELECT_HEAD, null)
            Vue.ls.set(SELECT_LEFT, null)
            this.$store.state.selectHead = null
          }
        })
      },
      cancel (e) {
        console.log('cancel', e)
        if (this.updateMemberDefaultInfo.defaultOrgId == null) {
          this.$message.error('请选择默认组织机构！')
          this.modal.visible = true
        } else {
          this.modal.visible = false
        }
      },
      afterClose () {
        if (this.updateMemberDefaultInfo.defaultOrgId == null) {
          this.modal.visible = true
        }
      },
      // 新密码和确认密码校验
      compareToFirstPassword (rule, value, callback) {
        const form = this.updateModal.form
        if (value && value !== form.getFieldValue('newPassword')) {
          callback(new Error('新密码和确认密码不一致'))
        } else {
          callback()
        }
      },
      // 更新密码
      updatePwdOk () {
        this.updateModal.form.validateFields((err, values) => {
          if (!err) {
            console.log('Received values of form: ', values)
            this.http.post('upmsApi', '/user/updatePwdNoLogin', {
              account: values.username,
              password: values.password,
              newPassword: values.newPassword
            }).then((res) => {
              if (res.success) {
                this.$message.info('修改密码成功！')
              }
              this.updateModal.visible = false
            })
          }
        })
      }
    }
  }
</script>

<style lang="less" scoped>
  .upms-head {
    height: 48px;
    line-height: 48px;
    text-align: center;

    .upms-head-txt {
      border-right: 1px solid #ebedf0;
      height: 20px;
      line-height: 20px;
      width: 100%;
      text-align: center;
      margin-top: 14px;
    }
  }
</style>
